import {getUserInfo, login} from "../../api/sys"
import md5 from "md5"
import {setItem,getItem, removeAllItem} from "../../utils/storage"
import {TOKEN,USERINFO} from "../../constant"
import router from "@/router"
export default {
    namespaced: true,

    state : ()=>({
        token : getItem(TOKEN) || "",
        userInfo:{}
    }),
    mutations : {
        setToken(state,token){
            state.token = token;
            setItem(TOKEN,token)
        },
        setUserInfo(state,userInfo){
            state.userInfo = userInfo
        }
    },
    
   actions : {
        login({commit},userInfo){
            let {username,password} = userInfo;
            return new Promise((resolve, reject) => {
                login({username,password: md5(password)}).then(response=>{
                    commit("setToken",response.token)
                    resolve()
                }).catch(error=>{
                    reject()
                })
            })
        },
        async getUserInfo(context){
            const res = await getUserInfo()
            this.commit('user/setUserInfo',res)
            return res
        },
        logout(){
            this.commit('user/setToken','')
            this.commit('user/setUserInfo',{})
            removeAllItem()
            router.push('/login')
        }
    }
}


